<!DOCTYPE html>
<!--引入thymeleaf模板引擎-->
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>中国梦想游-用户登录</title>
    <style type="text/css">
        #password {
            height: 30px;
            width: 165px;
            font-size: 15px;
        }

        #account {
            height: 20px;
            width: 156px;
        }

        #errorMsg {
            color: red; /*字体颜色*/
            font-weight: 700; /*加粗*/
            text-align: center; /*文字居中*/
        }

        /* 人脸识别相关样式 */
        .face-login-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            z-index: 1000;
            backdrop-filter: blur(5px);
        }

        .face-login-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 30px;
            border-radius: 15px;
            width: 420px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
        }

        #facePreview {
            width: 220px;
            height: 220px;
            margin: 20px auto;
            border: 2px solid #3480e2;
            border-radius: 50%;
            overflow: hidden;
            position: relative;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        #facePreview::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: 2px dashed #3480e2;
            border-radius: 50%;
            animation: pulse 2s infinite;
            opacity: 0.7;
            pointer-events: none;
        }

        @keyframes pulse {
            0% { transform: scale(1); opacity: 0.7; }
            50% { transform: scale(1.05); opacity: 1; }
            100% { transform: scale(1); opacity: 0.7; }
        }

        .login-buttons {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-top: 25px;
        }

        .log_b {
            padding: 0 24px;
            height: 40px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.2s ease;
            display: inline-flex;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;
        }

        .log_b:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .primary-btn {
            background-color: #3480e2;
            color: white;
        }

        .secondary-btn {
            background-color: #ffffff;
            color: #333;
            border: 1px solid #e0e0e0;
        }

        .status-message {
            padding: 12px;
            border-radius: 6px;
            margin: 15px 0;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .info-message {
            background-color: #e8f5e9;
            color: #2e7d32;
        }

        .loading-message {
            background-color: #fff3e0;
            color: #f57c00;
        }

        .error-message {
            background-color: #ffebee;
            color: #c62828;
        }

        .spinner {
            width: 16px;
            height: 16px;
            border: 2px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: currentColor;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    

    #errorMsg {
        color: red; /*字体颜色*/
        font-weight: 700; /*加粗*/
        text-align: center; /*文字居中*/
    }

    /* 人脸识别相关样式 */
    .face-login-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }

    .face-login-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: white;
        padding: 20px;
        border-radius: 5px;
        width: 400px;
        text-align: center;
    }

    #facePreview {
        width: 200px;
        height: 200px;
        margin: 10px auto;
        border: 1px solid #ccc;
        overflow: hidden;
    }

    #faceImage {
        margin: 10px 0;
    }

    .login-buttons {
        display: flex;
        gap: 10px;
        justify-content: center;
        margin-top: 10px;
    }
    </style>


    <!--引入static下的css文件和js文件-->
    <link href="/home/css/style.css" rel="stylesheet" type="text/css"/>
    <link href="/home/css/common.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="/home/js/jquery-3.5.1.js"></script>
    <script type="text/javascript" src="/home/js/vue.js"></script>
    <script type="text/javascript" src="/home/js/axios.js"></script>
    <script type="text/javascript" src="/home/js/config.js"></script>

    <script type="text/javascript">
        /***********验证用户名*************/
        function checkAccount() {
            let account = $("#username").val();
            if (account.trim() === "") {
                $("#errorMsg").text("用户名不能为空");
                return false;
            }
            return true;
        }

        /***********验证密码*************/
        function checkPassword() {
            let password = $("#password").val();
            if (password.trim() === "") {
                $("#errorMsg").text("密码不能为空");
                return false;
            }
            return true;
        }
    </script>
</head>
<body>
<!--引入顶部文件-->
<div th:replace="/home/header"></div>

<div class="b_wrap">

    <div class="current"><span>您当前的位置：</span>
        <a href="http://localhost:8080/index.html">首页</a> >
        <a href="/home/login.html">账号登录</a></div>
    <div class="login_w clearfix">
        <div class="login">
            <div class="login_t">用户登录
                <br>
                <span id="errorMsg" th:text="${errorMsg}  "></span>  <!--    错误提示   -->
            </div>

            <div class="login_con">
                <form id="login-form">
                    <table class="login_tab" width="270" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                            <td>账&nbsp;&nbsp;&nbsp;&nbsp;号：
                                <div style="height:13px;"></div>
                            </td>
                            <td>
                                <input type="text" name="username" id="username" value=""
                                       placeholder="用户名/邮箱/手机号" v-model="user.username" onblur="checkAccount()"><br>
                                <div id="z1" style="height:13px;"></div>
                            </td>
                        </tr>
                        <tr>
                            <td>密&nbsp;&nbsp;&nbsp;&nbsp;码：<br></td>
                            <td>
                                <input type="password" name="password" id="password" value="" placeholder="密码"
                                       v-model="user.password" onblur="checkPassword()"><br>
                            </td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td>
                                <div class="login-buttons">
                                    <input type="button" class="log_b primary-btn" value="账号登录" @click="onLogin"/>
                                    <input type="button" class="log_b secondary-btn" value="人脸识别登录"
                                           @click="showFaceLoginModal"/>
                                </div>
                            </td>
                        </tr>
                    </table>

                    <!-- 人脸识别登录模态框 - 只保留一个版本，并确保在Vue实例挂载点内部 -->
                    <div class="face-login-modal" id="faceLoginModal">
                        <div class="face-login-content">
                            <h3 style="color: #2c3e50; margin-bottom: 20px;">人脸识别登录</h3>
                            <div id="faceLoginMessage" class="status-message info-message">
                                <span>请将脸部对准摄像头</span>
                            </div>
                            <div id="facePreview">
                                <video id="cameraPreview" autoplay playsinline style="width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1);"></video>
                                <img id="previewFaceImg" src="" style="width: 100%; height: 100%; object-fit: cover; display: none;">
                            </div>
                            <div class="login-buttons">
                                <input type="button" id="captureBtn" class="log_b primary-btn" value="拍照" style="display: block;">
                                <input type="button" class="log_b secondary-btn" value="重新拍摄" @click="resetCamera" style="display: none;">
                                <input type="button" id="startRecognitionBtn" class="log_b primary-btn" value="开始识别" @click="startFaceRecognition" style="display: none;">
                                <input type="button" class="log_b secondary-btn" value="取消" @click="hideFaceLoginModal">
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <div class="login_b">
                <p style="text-align: right">没有登录账号？
                    <a class="free_zc" href="/home/register.html">免费注册</a>
                </p>
            </div>

        </div>
    </div>
</div>

<script>
    var login = new Vue({
        el: '#login-form',
        data: {
            user: {
                username: '',
                password: ''
            },
            faceImage: '', // 存储人脸照片的Base64编码
            cameraStream: null // 存储摄像头流对象
        },
        methods: {
            onLogin() {
                console.log(this.user);
                //使用axios库发送ajax请求
                //参数1：请求地址 ，参数2：请求数据
                axios.post("/home/login", this.user).then(response => {

                    console.log(response.data);
                    if (response.data.code === 200) {
                        alert("登陆成功： " + response.data.data.user.username + "     saToken:" + response.data.data.token);
                        // 保存完整的用户信息
                        localStorage.setItem("USER_ID", response.data.data.user.userId);
                        localStorage.setItem("USER_INFO", JSON.stringify(response.data.data.user));
                        //登录成功后跳转到首页
                        window.location.href = "/home/index.html";
                    } else {
                        alert(response.data.message);
                    }
                })
            },

            // 显示人脸识别登录模态框
            showFaceLoginModal() {
                console.log('显示人脸识别模态框');
                // 验证用户名是否输入
                if (!this.user.username.trim()) {
                    $("#errorMsg").text("请先输入用户名");
                    return;
                }

                // 重置模态框状态
                const modal = $("#faceLoginModal");
                const messageEl = $("#faceLoginMessage");
                const captureBtn = $("#captureBtn");
                const retakeBtn = $("input[value='重新拍摄']");
                const recognitionBtn = $("#startRecognitionBtn");
                const videoElement = document.getElementById('cameraPreview');
                const previewImg = $("#previewFaceImg");

                // 重置UI状态
                messageEl.html('<span>请将脸部对准摄像头</span>').removeClass().addClass('status-message info-message');
                previewImg.hide();
                videoElement.style.display = 'block';
                captureBtn.show();
                retakeBtn.hide();
                recognitionBtn.hide();
                this.faceImage = '';

                // 显示模态框并添加动画
                modal.show().find('.face-login-content').css('transform', 'translate(-50%, -50%) scale(0.9)');
                setTimeout(() => {
                    modal.find('.face-login-content').css('transform', 'translate(-50%, -50%) scale(1)');
                }, 10);

                // 访问摄像头
                this.accessCamera();

                // 添加拍照按钮点击事件
                const vm = this;
                captureBtn.off('click').on('click', function() {
                    // 显示加载状态
                    messageEl.html('<div class="spinner"></div><span>正在处理图片...</span>').removeClass().addClass('status-message loading-message');
                    captureBtn.prop('disabled', true);
                    setTimeout(() => {
                        vm.captureImage();
                        // 恢复按钮状态
                        captureBtn.prop('disabled', false);
                    }, 500);
                });
            },

            // 隐藏人脸识别登录模态框
            hideFaceLoginModal() {
                $("#faceLoginModal").hide();
                this.stopCamera();
            },

            // 重置摄像头
            resetCamera() {
                $("#previewFaceImg").hide();
                $("#cameraPreview").show();
                $("#captureBtn").show();
                $("#startRecognitionBtn").hide();
                this.faceImage = '';
                this.accessCamera();
            },

            // 访问摄像头
            accessCamera() {
                this.stopCamera(); // 先停止可能存在的摄像头流

                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    navigator.mediaDevices.getUserMedia({ video: true })
                        .then(stream => {
                            this.cameraStream = stream;
                            const videoElement = document.getElementById('cameraPreview');
                            videoElement.srcObject = stream;
                            $("#faceLoginMessage").text('请将脸部对准摄像头并点击拍照').css('color', 'blue');
                        })
                        .catch(error => {
                            console.error('无法访问摄像头:', error);
                            $("#faceLoginMessage").text('无法访问摄像头，请确保已授予摄像头权限').css('color', 'red');
                        });
                } else {
                    $("#faceLoginMessage").text('您的浏览器不支持摄像头访问').css('color', 'red');
                }
            },

            // 停止摄像头
            stopCamera() {
                if (this.cameraStream) {
                    this.cameraStream.getTracks().forEach(track => track.stop());
                    this.cameraStream = null;
                }
            },

            // 拍照
            captureImage() {
                const videoElement = document.getElementById('cameraPreview');
                const canvas = document.createElement('canvas');
                canvas.width = 220;
                canvas.height = 220;
                const context = canvas.getContext('2d');
                context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);

                // 将canvas内容转换为base64格式
                this.faceImage = canvas.toDataURL('image/jpeg').split(',')[1];

                // 显示预览图片，隐藏摄像头和拍照按钮
                $("#cameraPreview").hide();
                $("#previewFaceImg").attr('src', canvas.toDataURL('image/jpeg')).show();
                $("#captureBtn").hide();
                $("input[value='重新拍摄']").show();
                $("#startRecognitionBtn").show();
                
                // 更新状态消息
                $("#faceLoginMessage").html('<span>照片已拍摄，请点击开始识别</span>').removeClass().addClass('status-message info-message');
            },

            // 开始人脸识别登录
            startFaceRecognition() {
                console.log('开始识别按钮被点击');
                if (!this.faceImage) {
                    $("#faceLoginMessage").text('请先拍照').css('color', 'red');
                    return;
                }

                console.log('准备发送人脸识别请求');
                $("#faceLoginMessage").text('正在进行人脸识别，请稍候...').css('color', 'blue');

                // 构建请求数据
                const faceLoginData = {
                    username: this.user.username, // 使用输入的用户名
                    image: this.faceImage
                };

                console.log('发送人脸识别登录请求:', faceLoginData);

                // 发送人脸识别登录请求到后端
                axios.post('/home/faceLogin', faceLoginData).then(response => {
                    console.log('人脸识别登录响应:', response.data);

                    if (response.data.code === 200) {
                        $("#faceLoginMessage").text('人脸识别成功，正在登录...').css('color', 'green');

                        // 登录成功，保存完整的用户信息并跳转
                        localStorage.setItem("USER_ID", response.data.data.user.userId);
                        localStorage.setItem("USER_INFO", JSON.stringify(response.data.data.user));
                        setTimeout(() => {
                            this.hideFaceLoginModal();
                            window.location.href = "/home/index.html";
                        }, 1000);
                    } else {
                        $("#faceLoginMessage").text('人脸识别失败：' + response.data.message).css('color', 'red');
                    }
                }).catch(error => {
                    console.error('人脸识别登录请求失败:', error);
                    $("#faceLoginMessage").text('人脸识别服务异常，请稍后再试').css('color', 'red');
                });
            }
        },
        mounted() {
            console.log('Vue实例已挂载');
            // 点击模态框外部关闭
            $(document).on('click', function (event) {
                if ($(event.target).is('#faceLoginModal')) {
                    this.hideFaceLoginModal();
                }
            }.bind(this));
        }
    })
</script>
<!--引入底部footer.html文件-->
<div th:replace="/home/footer"></div>
</body>
</html>
